import { NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import prisma from '@/lib/prisma'
import { SignJWT } from 'jose'

const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'your-secret-key')
const JWT_EXPIRATION = process.env.JWT_EXPIRATION || '1h'

export async function POST(request: Request) {
  try {
    const { email, password } = await request.json()

    // Validate input
    if (!email || !password) {
      return NextResponse.json(
        { error: '邮箱和密码不能为空' },
        { status: 400 }
      )
    }

    // Find user by email
    const user = await prisma.vms_user.findFirst({
      where: { email: email as string }
    })

    if (!user) {
      return NextResponse.json(
        { error: '邮箱或密码错误，请检查后重试' },
        { status: 401 }
      )
    }
    if (!user.password) {
        return NextResponse.json(
          { error: '邮箱或密码错误，请检查后重试' },
          { status: 401 }
        );
      }
    const passwordMatch = await bcrypt.compare(password, user.password);
    if (!passwordMatch) {
      return NextResponse.json(
        { error: '邮箱或密码错误，请检查后重试' },
        { status: 401 }
      )
    }

    // Generate JWT token using jose
    const token = await new SignJWT({
      id: user.id,
      email: user.email,
      name: user.name,
      roles: user.roles,
      vip_type: user.vip_type,
      vip_end_time: user.vip_end_time?.toISOString()
    })
      .setProtectedHeader({ alg: 'HS256' })
      .setExpirationTime(JWT_EXPIRATION)
      .sign(JWT_SECRET)

    // Return success response with token and user data (without password)
    const { password: _, ...userWithoutPassword } = user
    
    // 创建响应
    const response = NextResponse.json(
      { 
        ...userWithoutPassword,
        token 
      }, 
      { status: 200 }
    )
    
    // 设置cookie
    response.cookies.set('token', token, {
      httpOnly: false, // 改为false，让前端也能读取
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 7 * 24 * 60 * 60, // 7天
      path: '/'
    })
    
    return response

  } catch (error) {
    console.error('Login error:', error)
    return NextResponse.json(
      { error: '服务器内部错误，请稍后重试' },
      { status: 500 }
    )
  }
}
